package com.heatup.apt.api.service.impl;

import com.baomidou.mybatisplus.mapper.*;
import com.heatup.apt.api.service.*;
import com.heatup.apt.common.constants.*;
import com.heatup.apt.common.dao.*;
import com.heatup.apt.common.dao.coach.*;
import com.heatup.apt.common.dao.redis.*;
import com.heatup.apt.common.dao.user.*;
import com.heatup.apt.common.util.*;
import com.heatup.apt.model.api.*;
import com.heatup.apt.model.coach.*;
import com.heatup.apt.model.course.*;
import com.heatup.apt.model.order.*;
import com.heatup.apt.model.product.*;
import com.heatup.apt.model.user.*;
import com.heatup.apt.model.weixin.*;
import org.slf4j.*;
import org.springframework.stereotype.*;

import javax.annotation.*;
import java.text.*;
import java.util.*;


@Service
public class TemplateSendServiceImpl implements TemplateSendService {
    private static final Logger logger = LoggerFactory.getLogger(TemplateSendServiceImpl.class);
    @Resource
    private TokenMapper tokenMapper;
    @Resource
    private TokenRedisDao tokenRedisDao;
    @Resource
    private OrderInfoResultMapper orderInfoResultMapper;
    @Resource
    private CourseScheduleMapper courseScheduleMapper;
    @Resource
    private UserDiscountMapper userDiscountMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserProductServiceMapper userProductServiceMapper;
    @Resource
    private ProductServiceDetailMapper productServiceDetailMapper;
    @Resource
    private ProductServiceMapper productServiceMapper;
    @Resource
    private VipPurchaseLogMapper vipPurchaseLogMapper;
    @Resource
    private CoachInfoMapper coachInfoMapper;
    @Resource
    private CourseCoachMapper courseCoachMapper;


    /**
     * 预约排队通知
     */
    @Override
    public void sendOrderWaitTemplateMsg(OrderInfo orderInfo) {
        logger.info("==================== sendWaitSuccTemplateMsg start==========================");
        OrderInfoResultModel orderInfoResult = (OrderInfoResultModel) orderInfo;
        Map<Object, Object> beforeParams = new HashMap<Object, Object>();
        beforeParams.put("orderId", orderInfoResult.getId());
        beforeParams.put("serviceId", orderInfoResult.getServiceId());
        int beforeWaitNum = orderInfoResultMapper.queryBeforeWaitNum(beforeParams);
        String tourl = MessageFormat.format(TemplateConstants.TEMPLATE_TO_URL_ORDER, orderInfo.getOrderType(),
                String.valueOf(orderInfo.getId()));
        logger.info("==========sendOrderWaitTemplateMsg to url is : " + tourl);
        try {
            Template template = new Template();
            template.setToUser(orderInfoResult.getUserInfo().getOpenid());
            template.setTemplateId(TemplateConstants.USER_WAIT_SUCCESS_TIPS);
            template.setTopColor("#333");
            template.setUrl(tourl);
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            paras.add(new TemplateParam("first", "您好，您已支付成功，前面还有" + beforeWaitNum + "人排队，如有人取消您将排队成功。", "#333"));
            paras.add(new TemplateParam("keyword1", orderInfoResult.getServicePrice().getServiceName().trim(), "#333"));
            paras.add(new TemplateParam("keyword2", getOrderStartTimeByOrderType(orderInfoResult), "#333"));
            paras.add(new TemplateParam("remark", "如到达开课时间仍未排队成功，系统将自动取消订单并给您退款。如有任何疑问，可联系客服：0755-86629280。", "#333"));
            template.setTemplateParamList(paras);
            new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("==================== sendWaitSuccTemplateMsg end==========================");
    }

    /**
     * @param backMoneyFlag 1:需要退款
     * @param orderId       ：订单ID
     * @author EarvinWoo 取消订单模板消息接口
     */
    @Override
    public void sendCancelOrderTemplateMsg(String backMoneyFlag, Integer orderId) {

        logger.info("==================== sendCancelOrderTemplateMsg start==========================");
        logger.info("SendCancelOrderTemplateMsg Method Param is " + " backMoneyFlag:" + backMoneyFlag + " orderId:"
                + orderId);
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            String tourl = MessageFormat.format(TemplateConstants.TEMPLATE_TO_URL_ORDER, orderInfo.getOrderType(),
                    String.valueOf(orderInfo.getId()));
            logger.info("==========sendCancelOrderTemplateMsg to url is : " + tourl);
            int orderType = orderInfo.getOrderType();
            // 订单类型(0普通订单 1团课订单 2私教订单 3趣营订单 4自助健身 5会员订单)
            String orderTypeName = conveterOrderTypeName(orderType);
            Template template = new Template();
            template.setToUser(orderInfo.getUserInfo().getOpenid());
            template.setTemplateId(TemplateConstants.USER_ORDER_CANCEL_TIPS);
            template.setTopColor("#333");
            template.setUrl(tourl);
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            String firstContent = "您好，您的订单取消成功！";
            // 根据是否退款来显示不同信息，1表示可退
            if ("1".equals(backMoneyFlag)) {
                if(orderInfo.getOrderType().intValue()==OrderContants.OrderType.team_course.getIndex()||
                        orderInfo.getOrderType().intValue()==OrderContants.OrderType.selffit.getIndex()){
                    firstContent="您好，您的订单取消成功！还有多种精彩课程仍然等你来约哦！";
                }else if(orderInfo.getOrderType().intValue()==OrderContants.OrderType.fun_camp.getIndex()){
                    firstContent="您好，您的订单取消成功！符合退款条件的订单，金额将即时退回您的代金卡账户。";
                }
                paras.add(new TemplateParam("keyword5", String.valueOf(orderInfo.getAmount()), "#333"));

            } else {
                if(orderInfo.getOrderType().intValue()==OrderContants.OrderType.team_course.getIndex()||
                        orderInfo.getOrderType().intValue()==OrderContants.OrderType.selffit.getIndex()){
                    firstContent="您好，您的订单取消成功！还有多种精彩课程仍然等你来约哦！";
                }else if(orderInfo.getOrderType().intValue()==OrderContants.OrderType.fun_camp.getIndex()){
                    firstContent="您好，您的订单取消成功！训练营成营后，开课前48小时内取消预订将不予退款。";
                }

                paras.add(new TemplateParam("keyword5", "0", "#333"));

            }
            paras.add(new TemplateParam("first", firstContent, "#333"));
            paras.add(new TemplateParam("remark", "如有任何疑问，可联系客服：0755-86629280。", "#333"));
            paras.add(new TemplateParam("keyword1", orderInfo.getOrderNumber(), "#333"));
            paras.add(new TemplateParam("keyword2", orderTypeName, "#333"));
            paras.add(new TemplateParam("keyword3", sdf.format(orderInfo.getCreatedTime()), "#333"));// 下单时间
            paras.add(new TemplateParam("keyword4", sdf.format(new Date()), "#333"));// 取消时间
            template.setTemplateParamList(paras);
            new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

        logger.info("==================== sendCancelOrderTemplateMsg end==========================");

    }

    private String conveterOrderTypeName(int orderType) {
        String orderTypeName = "普通订单";
        if (orderType == OrderContants.OrderType.team_course.getIndex()) {
            orderTypeName = OrderContants.OrderType.team_course.getTitle();
        } else if (orderType == OrderContants.OrderType.fun_camp.getIndex()) {
            orderTypeName = OrderContants.OrderType.fun_camp.getTitle();
        } else if (orderType == OrderContants.OrderType.selffit.getIndex()) {
            orderTypeName = OrderContants.OrderType.selffit.getTitle();
        } else if (orderType == OrderContants.OrderType.pt.getIndex()) {
            orderTypeName = OrderContants.OrderType.pt.getTitle();
        } else if (orderType == OrderContants.OrderType.vip_order.getIndex()) {
            orderTypeName = OrderContants.OrderType.vip_order.getTitle();
        } else if (orderType == OrderContants.OrderType.physical_examination.getIndex()) {
            orderTypeName = OrderContants.OrderType.physical_examination.getTitle();
        } else if (orderType == OrderContants.OrderType.secret_experience.getIndex()) {
            orderTypeName = OrderContants.OrderType.secret_experience.getTitle();
        } else if (orderType == OrderContants.OrderType.private_bespeak.getIndex()) {
            orderTypeName = OrderContants.OrderType.private_bespeak.getTitle();
        }
        return orderTypeName;
    }

    /**
     * 订单预订成功通知
     * @author EarvinWoo
     */
    @Override
    public void sendBookingSuccTemplateMsg(Integer orderId, String orderStatus) {
        // TODO Auto-generated method stub

        logger.info("==================== sendBookingSuccTemplateMsg start==========================");
        logger.info("sendBookingSuccTemplateMsg Method Param is " + " orderId:" + orderId);
        try {
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            String tourl = getOrderURLByOrderType(orderInfo);
            logger.info("==========sendBookingSuccTemplateMsg to url is : " + tourl);
            if (orderInfo != null) {
                Template template = new Template();
                template.setToUser(orderInfo.getUserInfo().getOpenid());
                template.setTemplateId(TemplateConstants.ORDER_BOOK_SUCCESS_TIPS);
                template.setTopColor("#333");
                template.setUrl(tourl);
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                if (OrderContants.OrderStatus.WAIT.getStatus().equals(orderStatus)) {
                    paras.add(new TemplateParam("first", "亲，您的排队订单已排队成功！课程开始前我们将及时通知您，请保持手机畅通！！", "#333"));
                } else {
                    paras.add(new TemplateParam("first", "亲，您的订单已支付成功！课程开始前我们将及时通知您，请保持手机畅通！", "#333"));
                }
                paras.add(new TemplateParam("keyword1", orderInfo.getOrderNumber(), "#333"));
                paras.add(new TemplateParam("keyword2", conveterOrderTypeName(orderInfo.getOrderType()), "#333"));
                paras.add(new TemplateParam("keyword3", orderInfo.getServicePrice().getServiceName().trim(), "#333"));
                paras.add(new TemplateParam("keyword4", orderInfo.getAmount().toString(), "#333"));
                paras.add(new TemplateParam("keyword5", getOrderStartTimeByOrderType(orderInfo), "#333"));
                paras.add(new TemplateParam("remark",
                        "运动时请带好运动装备，做好充足的热身准备，开始运动前半个小时忌大量饮水进食。如有任何疑问，可联系客服：0755-86629280。", "#333"));
                template.setTemplateParamList(paras);
                logger.info("===============>> template is :" + template.toJSON());
                new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();

            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("==================== sendBookingSuccTemplateMsg end==========================");
    }


    /**
     * 订单预订成功通知
     * @author EarvinWoo
     */
    @Override
    public void sendBookingMealSuccTemplateMsg(Integer orderId, String orderStatus) {
        // TODO Auto-generated method stub

        logger.info("==================== sendBookingSuccTemplateMsg start==========================");
        logger.info("sendBookingSuccTemplateMsg Method Param is " + " orderId:" + orderId);
        try {
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            String tourl = getOrderURLByOrderType(orderInfo);
            logger.info("==========sendBookingSuccTemplateMsg to url is : " + tourl);
            if (orderInfo != null) {
                Template template = new Template();
                template.setToUser(orderInfo.getUserInfo().getOpenid());
                template.setTemplateId(TemplateConstants.ORDER_BOOK_SUCCESS_TIPS);
                template.setTopColor("#333");
                template.setUrl(tourl);
                List<TemplateParam> paras = new ArrayList<TemplateParam>();

                    paras.add(new TemplateParam("first", "亲，您的订单已支付成功！我们将为你奉上美味的营养健康餐！", "#333"));

                paras.add(new TemplateParam("keyword1", orderInfo.getOrderNumber(), "#333"));
                paras.add(new TemplateParam("keyword2", "餐饮", "#333"));
                paras.add(new TemplateParam("keyword3", "健康餐", "#333"));
                paras.add(new TemplateParam("keyword4", orderInfo.getAmount().toString(), "#333"));
                paras.add(new TemplateParam("keyword5", getOrderStartTimeByOrderType(orderInfo), "#333"));
                paras.add(new TemplateParam("remark",
                        "餐食预订后不可取消，请按时就餐，如有任何疑问，可联系客服：0755-86629280。", "#333"));
                template.setTemplateParamList(paras);
                logger.info("===============>> template is :" + template.toJSON());
                new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        logger.info("==================== sendBookingSuccTemplateMsg end==========================");
    }

    /**
     * 根据订单类型不同，取不同的订单开始时间的模板消息显示信息
     *
     * @param orderInfo
     * @return 订单开始时间
     */
    private String getOrderStartTimeByOrderType(OrderInfoResultModel orderInfo) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String courseStartTime = "课程开始时间请查看订单详情信息";
        try {
            // 根据课程类型不同，去不同的课程开始时间
            if (StringUtil.isEquals(OrderContants.OrderType.fun_camp.getType(), orderInfo.getOrderType().toString())
                    || StringUtil.isEquals(OrderContants.OrderType.team_course.getType(),
                    orderInfo.getOrderType().toString())) {
//				CourseScheduleExample courseScheduleExample = new CourseScheduleExample();
//				courseScheduleExample.or().andCourseIdEqualTo(orderInfo.getServicePrice().getCourseId());
//				List<CourseSchedule> courseSchedules = courseScheduleMapper.selectByExample(courseScheduleExample);


                CourseSchedule courseScheduleDB = new CourseSchedule();
                courseScheduleDB.setCourseId(orderInfo.getServicePrice().getCourseId());
                EntityWrapper<CourseSchedule> entityWrapper = new EntityWrapper<>(courseScheduleDB);
                List<CourseSchedule> courseSchedules = courseScheduleMapper.selectList(entityWrapper);
                CourseSchedule courseSchedule = null;
                if (courseSchedules != null && courseSchedules.size() > 0) {
                    courseSchedule = courseSchedules.get(0);
                }
                Date startTime = courseSchedule.getStartTime();
                if (startTime != null) {
                    courseStartTime = sdf.format(startTime);
                }
            } else if (StringUtil.isEquals(OrderContants.OrderType.pt.getType(), orderInfo.getOrderType().toString())) {
                courseStartTime = "请与教练确认具体上课时间";
            } else if (StringUtil.isEquals(OrderContants.OrderType.physical_examination.getType(), orderInfo.getOrderType().toString())) {
                courseStartTime = "请与教练确认具体上课时间";
            } else if (StringUtil.isEquals(OrderContants.OrderType.secret_experience.getType(), orderInfo.getOrderType().toString())) {
                courseStartTime = "请与教练确认具体上课时间";
            } else if (StringUtil.isEquals(OrderContants.OrderType.selffit.getType(),
                    orderInfo.getOrderType().toString())) {
                OrderDetail orderDetail = orderInfo.getOrderDetail();
                if (orderDetail != null) {
                    Date startTime = orderDetail.getStartTime();
                    if (startTime != null)
                        courseStartTime = sdf.format(orderDetail.getStartTime());
                }
            }
        } catch (Exception e) {
            logger.info(e.getMessage());
        }
        return courseStartTime;
    }

    @Override
    public void sendOpenVIPSuccTemplateMsg(Integer orderId) {
        logger.info("==================== sendOpenVIPSuccTemplateMsg start==========================");
        logger.info("sendBookingSuccTemplateMsg Method Param is orderId:" + orderId);
        try {
            String tourl = TemplateConstants.TEMPLATE_TO_URL_VIP_ORDER;
            logger.info("==========sendOpenVIPSuccTemplateMsg to url is : " + tourl);
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            UserInfo userInfo = orderInfo.getUserInfo();
            //UserDiscount userDiscount = userDiscountMapper.getUserDiscountById(orderInfo.getServiceId());
            ProductServiceDetail psd = productServiceDetailMapper.selectById(orderInfo.getServiceId());
            ProductService ps = productServiceMapper.selectById(psd.getPdProductServiceId());
            UserProductService ups = userProductServiceMapper.queryUserProductServiceByUserIdAndType(orderInfo.getUserId(), ps.getPServiceType());
            VipPurchaseLog vipPurchaseLog = vipPurchaseLogMapper.quertVipPurchaseLogByOrderId(orderId);
            String orderTypeName = "";
            String vaildTimePeriod = "";
            String title = "您好，您已成功开通";
            String vipType = "";
            if (psd != null) {
                if (ps.getId() == 1) {
                    orderTypeName = psd.getPdRemarks();
                    title = title + "檬会员！";
                    vipType = "檬会员";
                } else {
                    orderTypeName = "1个月";
                    title = title + "“" + psd.getPdRemarks() + "”！";
                    vipType = psd.getPdRemarks();
                }

            }
            try {
                /*vaildTimePeriod = DateUtils.format(userInfo.getVipStartTime(), DateUtils.datePattern) + "至"
						+ DateUtils.format(DateUtils.AddDays(userInfo.getVipEndTime(),-1), DateUtils.datePattern);*/
                vaildTimePeriod = DateUtils.format(vipPurchaseLog.getStartTime(), DateUtils.datePattern) + "至"
                        + DateUtils.format(DateUtils.AddDays(vipPurchaseLog.getEndTime(), -1), DateUtils.datePattern);
            } catch (Exception e) {
                logger.info(e.getMessage());
            }

            Template template = new Template();
            template.setToUser(orderInfo.getUserInfo().getOpenid());
            template.setTemplateId(TemplateConstants.OPEN_VIP_USER_TIPS);
            template.setTopColor("#333");
            template.setUrl(tourl);
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            paras.add(new TemplateParam("first", title, "#333"));
            paras.add(new TemplateParam("keyword1", orderInfo.getOrderNumber(), "#333"));
            paras.add(new TemplateParam("keyword2", vipType, "#333"));
            paras.add(new TemplateParam("keyword3", orderInfo.getAmount().toString(), "#333"));
            paras.add(new TemplateParam("keyword4", orderTypeName, "#333"));
            paras.add(new TemplateParam("keyword5", vaildTimePeriod, "#333"));
            paras.add(new TemplateParam("remark", "如有任何疑问，可联系檬客服：0755-86629280。", "#333"));
            template.setTemplateParamList(paras);

            new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

        logger.info("==================== sendOpenVIPSuccTemplateMsg end==========================");

    }

    @Override
    public void sendCashCardRechargeSucc(UserAccountRecharge userAccountRecharge) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info("================>> 代金卡充值成功提醒  sendCashCardRechargeSucc ");
        try {
            if (userAccountRecharge != null) {
                String rechargeType = userAccountRecharge.getRechargeType().intValue() == 1 ? "微信支付" : "兑换码充值";
                UserInfo userInfo = userInfoMapper.selectById(userAccountRecharge.getUserId());
                Template template = new Template();
                template.setToUser(userInfo.getOpenid());
                template.setTemplateId(TemplateConstants.CASHCARD_RECHARGE_TIPS);
                template.setTopColor("#333");
                template.setUrl(TemplateConstants.TEMPLATE_TO_CASH_CARD_RECHARGE_URL);
                List<TemplateParam> paras = new ArrayList<TemplateParam>();
                paras.add(new TemplateParam("first", "您好，您的代金卡充值成功！", "#333"));
                paras.add(new TemplateParam("keyword1", userAccountRecharge.getFaceAmt().toString(), "#333"));// 充值金额
                paras.add(new TemplateParam("keyword2", sdf.format(userAccountRecharge.getCreateTime()), "#333"));
                paras.add(new TemplateParam("keyword3", rechargeType, "#333"));
                paras.add(new TemplateParam("keyword4", userInfo.getAccountAmt().toString(), "#333"));// 实到金额
                paras.add(new TemplateParam("remark", "感谢您的使用，点击可查看详情", "#333"));
                template.setTemplateParamList(paras);
                new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
            }
        } catch (Exception e) {
            logger.error("============>> 代金卡充值模板消息发送失败 ：" + e.toString() + e.getCause(), e);
        }
    }

    /**
     * 开通会员成功 新方法
     * 因为开始时间和结束时间之前取错了
     * 应该是开通的有效时间而不是用户拥有卡的有效时间
     */
    @Override
    public void sendOpenVIPSuccTemplateMsgNew(Integer orderId, Date startDate, Date endDate, Integer days) {
        logger.info("==================== sendOpenVIPSuccTemplateMsg start==========================");
        logger.info("sendBookingSuccTemplateMsg Method Param is orderId:" + orderId);
        try {
            String tourl = TemplateConstants.TEMPLATE_TO_URL_VIP_ORDER;
            logger.info("==========sendOpenVIPSuccTemplateMsg to url is : " + tourl);
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            UserInfo userInfo = orderInfo.getUserInfo();
            //UserDiscount userDiscount = userDiscountMapper.getUserDiscountById(orderInfo.getServiceId());
            ProductServiceDetail psd = productServiceDetailMapper.selectById(orderInfo.getServiceId());
            ProductService ps = productServiceMapper.selectById(psd.getPdProductServiceId());
            UserProductService ups = userProductServiceMapper.queryUserProductServiceByUserIdAndType(orderInfo.getUserId(), ps.getPServiceType());
            String orderTypeName = "";
            String vaildTimePeriod = "";
            String title = "您好，您已成功开通";
            String vipType = "";
            if (ps != null) {
                if (ps.getPServiceType().equals("2") ) {
                    orderTypeName = psd.getPdRemarks();
                    title = title + "围裙健身会员！";
                    vipType = "围裙健身会员";
                } else {
                    orderTypeName = psd.getPdRemarks();
                    title = title + "“" + ps.getPServiceName() + "”。团课、自助随时免费约起，还有精品小班私教等你来战！";
                    vipType = ps.getPServiceName();
                }

            }
            try {
                vaildTimePeriod = DateUtils.format(startDate, DateUtils.datePattern) + "至"
                        + DateUtils.format(DateUtils.AddDays(endDate, -1), DateUtils.datePattern);
            } catch (Exception e) {
                logger.info(e.getMessage());
            }

            Template template = new Template();
            template.setToUser(orderInfo.getUserInfo().getOpenid());
            template.setTemplateId(TemplateConstants.OPEN_VIP_USER_TIPS);
            template.setTopColor("#333");
            template.setUrl(tourl);
            List<TemplateParam> paras = new ArrayList<TemplateParam>();
            paras.add(new TemplateParam("first", title, "#333"));
            paras.add(new TemplateParam("keyword1", orderInfo.getOrderNumber(), "#333"));
            paras.add(new TemplateParam("keyword2", vipType, "#333"));
            paras.add(new TemplateParam("keyword3", orderInfo.getAmount().toString(), "#333"));
            paras.add(new TemplateParam("keyword4", orderTypeName, "#333"));
            paras.add(new TemplateParam("keyword5", vaildTimePeriod, "#333"));
            paras.add(new TemplateParam("remark", "如有任何疑问，可联系客服：0755-86629280。", "#333"));
            template.setTemplateParamList(paras);

            new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
        } catch (Exception e) {
            logger.info(e.getMessage());
        }

        logger.info("==================== sendOpenVIPSuccTemplateMsg end==========================");

    }

    /**
     * 私教订单教练通知模板消息
     *
     * @param orderId
     */
    @Override
    public void sendBookSuccOrderForCoach(Integer orderId) {
        logger.info("======私教订单教练通知模板消息 开始 === sendBookSuccOrderForCoach : orderId = " + orderId);
        try {
            OrderInfoResultModel orderInfo = orderInfoResultMapper.selectByOrderId(orderId);
            //私教体验订单，体测订单，预约订单
            if (orderInfo != null) {
                if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.physical_examination.getIndex()
                        || orderInfo.getOrderType().intValue() == OrderContants.OrderType.secret_experience.getIndex()
                        || orderInfo.getOrderType().intValue() == OrderContants.OrderType.private_bespeak.getIndex()
                        || orderInfo.getOrderType().intValue() == OrderContants.OrderType.pt.getIndex()) {

                    Integer coachId = orderInfo.getOrderDetail().getCoachId();
                    if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.pt.getIndex()) {
                        List<CourseCoach> courseCoaches = courseCoachMapper.selectByCourseId(orderInfo.getServicePrice().getCourseId());
                        if(courseCoaches!=null && courseCoaches.size()>0){
                            coachId = courseCoaches.get(0).getCoachId();
                        }
                    }
                    if (coachId != null && coachId > 0) {
                        CoachInfo coachInfo = coachInfoMapper.selectById(coachId);
                        List<UserInfo> coachUsers = userInfoMapper.selectUsersByMobile(coachInfo.getMobile());
                        if (coachUsers != null) {
                            UserInfo coachUser = coachUsers.get(0);
                            Template template = new Template();
                            template.setToUser(coachUser.getOpenid());
                            template.setTemplateId(TemplateConstants.ORDER_BOOK_SUCC_NOTICE_COACH_TIPS);
                            template.setTopColor("#333");
                            String tourl = "";
                            List<TemplateParam> paras = new ArrayList<TemplateParam>();
                            String title = "";// 课程名称
                            String courseType = "";// 课程类型
                            if(orderInfo.getOrderType().intValue() == OrderContants.OrderType.pt.getIndex()){
                                title = "亲爱的" + coachInfo.getNickName() + "教练，有学员预订了您的私教课";
                                courseType=orderInfo.getServicePrice().getServiceName();
                                tourl=TemplateConstants.COACH_PRIVATE_LIST;
                            }
                            else if (OrderContants.OrderType.private_bespeak.getIndex() == orderInfo.getOrderType()) {
                                title = "亲爱的" + coachInfo.getNickName() + "教练，有学员预订了您的私教咨询";
                                courseType = "私教咨询";
                                tourl=TemplateConstants.COACH_PB_LIST;
                            } else if (orderInfo.getOrderType().intValue() == OrderContants.OrderType.physical_examination.getIndex()){
                                title = "亲爱的" + coachInfo.getNickName() + "教练，有学员预订了您的" + orderInfo.getServicePrice().getServiceName();
                                courseType = orderInfo.getServicePrice().getServiceName();
                                tourl=TemplateConstants.COACH_PE_LIST;
                            }else{
                                title = "亲爱的" + coachInfo.getNickName() + "教练，有学员预订了您的" + orderInfo.getServicePrice().getServiceName();
                                courseType = orderInfo.getServicePrice().getServiceName();
                                tourl=TemplateConstants.COACH_SE_LIST;
                            }

                            template.setUrl(tourl);
                            paras.add(new TemplateParam("first", title, "#333"));
                            paras.add(new TemplateParam("keyword1", orderInfo.getUserInfo().getNickName(), "#333"));
                            paras.add(new TemplateParam("keyword2", DateUtils.format(orderInfo.getCreatedTime(), DateUtils.dateTimePatternChinese), "#333"));
                            paras.add(new TemplateParam("keyword3", orderInfo.getUserInfo().getMobile(), "#333"));
                            paras.add(new TemplateParam("keyword4", courseType, "#333"));
                            paras.add(new TemplateParam("remark", "请尽快与学员取得联系。", "#333"));
                            template.setTemplateParamList(paras);
                            new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("发送私教订单教练通知模板消息失败", e);
        }
        logger.info("======私教订单教练通知模板消息 结束 === sendBookSuccOrderForCoach :");
    }

    public String getOrderURLByOrderType(OrderInfo orderInfo) {
        String orderURL = "";
        if (OrderContants.OrderType.physical_examination.getIndex() == orderInfo.getOrderType().intValue()
                || OrderContants.OrderType.secret_experience.getIndex() == orderInfo.getOrderType().intValue()) {
            orderURL = MessageFormat.format(TemplateConstants.PRIVATE_TEMPLATE_TO_URL_ORDER, orderInfo.getOrderType(),
                    String.valueOf(orderInfo.getId()));
        } else {
            orderURL = MessageFormat.format(TemplateConstants.TEMPLATE_TO_URL_ORDER, orderInfo.getOrderType(),
                    String.valueOf(orderInfo.getId()));
        }
        return orderURL;
    }
    
    /**
     * 发送购餐成功之后的微信模板消息
     */
	@Override
	public void sendPayMealOrderMsg(OrderInfoResultModel orderInfoResultModel, UserInfo userInfo) {
		
		String title = "亲，您已支付成功！工作人员将用最短的时间为你献上美味健康的食物，请你耐心等候！";
		String type = "餐饮";
		String payAmt = orderInfoResultModel.getAmount().toString();
		Date payTime = orderInfoResultModel.getPayTime();
		String remark = "如有任何疑问，可联系客服：0755-86629280。";
		
		
		// 微信模板消息
		Template template = new Template();
		// 发给的用户
		template.setToUser(userInfo.getOpenid());
		template.setTemplateId(TemplateConstants.MEAL_ORDER_SUCCESS_TIPS);
		template.setTopColor("#333");
		// 跳转详情
		template.setUrl(TemplateConstants.TEMPLATE_TO_CASH_CARD_RECHARGE_URL);
		
		
		// 构建内容 
		List<TemplateParam> paras = new ArrayList<TemplateParam>();
		paras.add(new TemplateParam("first", title, "#333"));
		paras.add(new TemplateParam("keyword1", type, "#333"));
		paras.add(new TemplateParam("keyword2",payAmt, "#333"));
		paras.add(new TemplateParam("keyword3",DateUtils.format(orderInfoResultModel.getCreatedTime(), DateUtils.dateTimePatternChinese), "#333"));
		paras.add(new TemplateParam("remark", remark, "#333"));
		
		template.setTemplateParamList(paras);
		new Thread(new SendTemplateThread(template, tokenMapper, tokenRedisDao)).start();
		
	}


}
